package com.jing21.learn.basic.controller;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成二维码
 *
 * @author zhengjing
 * @version 1.0
 */
public final class QRCodeUtil {

    private static Logger logger = LoggerFactory.getLogger(QRCodeUtil.class);


    /**
     * 默认二维码大小
     */
    public static final int QR_CODE_SIZE = 300;

    public static final String QR_CODE_FORMAT = "JPEG";

    /**
     * 创建二维码串
     *
     * @param content 二维码字符串的值
     * @return
     */
    public static BufferedImage createQrCode(String content) {

        return createQrCode(content, QR_CODE_SIZE);
    }

    /**
     * 创建二维码并写到指定输出流
     *
     * @param content      二维码字符串的值
     * @param outputStream 输出流
     * @return 是否成功
     */
    public static boolean createQrCode(String content, OutputStream outputStream) {

        BufferedImage qrCode = createQrCode(content, QR_CODE_SIZE);
        try {
            if (qrCode != null) {
                return ImageIO.write(qrCode, QR_CODE_FORMAT, outputStream);
            }
        } catch (IOException e) {
            logger.error("将图片写到输出流失败：{}", e.getMessage(), e);
        }
        return false;
    }

    /**
     * 创建二维码
     *
     * @param content     生成的字符串
     * @param qrCodeSize  二维码大小
     * @return 二维码图片对象
     */
    public static BufferedImage createQrCode(String content, int qrCodeSize) {

        try {
            int width = qrCodeSize; // 图像宽度
            int height = qrCodeSize; // 图像高度
            Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, width, height, hints);// 生成矩阵
            return MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (Exception e) {
            logger.error("创建二维码出错:{}", e.getMessage(), e);
        }

        return null;
    }

    /**
     * 读二维码并输出携带的信息
     */
    public static String readQrCode(InputStream inputStream){
        BufferedImage image;
        try {
            image = ImageIO.read(inputStream);
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
            return result.getText();
        } catch (Exception e) {
            logger.error("解析二维码失败：{}",e.getMessage(),e);
        }
        return null;

    }

}